using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SheLife.Domain.Entities;
using SheLife.Domain.Interfaces;

namespace SheLife.Infrastructure.Repositories
{
    public class SkincareAnalysisRepository : ISkincareAnalysisRepository
    {
        private readonly SheLifeDbContext _context;

        public SkincareAnalysisRepository(SheLifeDbContext context)
        {
            _context = context;
        }

        public async Task<SkincareAnalysis> GetByIdAsync(int id)
        {
            return await _context.SkincareAnalyses.FindAsync(id);
        }

        public async Task<IEnumerable<SkincareAnalysis>> GetByUserIdAsync(int userId)
        {
            return await _context.SkincareAnalyses
                .Where(a => a.UserId == userId)
                .OrderByDescending(a => a.AnalysisDate)
                .ToListAsync();
        }

        public async Task<IEnumerable<SkincareAnalysis>> GetByUserIdAndDateRangeAsync(int userId, DateTime startDate, DateTime endDate)
        {
            return await _context.SkincareAnalyses
                .Where(a => a.UserId == userId && 
                           a.AnalysisDate >= startDate && 
                           a.AnalysisDate <= endDate)
                .OrderByDescending(a => a.AnalysisDate)
                .ToListAsync();
        }

        public async Task<SkincareAnalysis> GetLatestByUserIdAsync(int userId)
        {
            return await _context.SkincareAnalyses
                .Where(a => a.UserId == userId)
                .OrderByDescending(a => a.AnalysisDate)
                .FirstOrDefaultAsync();
        }

        public async Task<SkincareAnalysis> AddAsync(SkincareAnalysis analysis)
        {
            analysis.CreatedAt = DateTime.UtcNow;
            await _context.SkincareAnalyses.AddAsync(analysis);
            await _context.SaveChangesAsync();
            return analysis;
        }

        public async Task UpdateAsync(SkincareAnalysis analysis)
        {
            analysis.UpdatedAt = DateTime.UtcNow;
            _context.Entry(analysis).State = EntityState.Modified;
            await _context.SaveChangesAsync();
        }

        public async Task DeleteAsync(int id)
        {
            var analysis = await GetByIdAsync(id);
            if (analysis != null)
            {
                _context.SkincareAnalyses.Remove(analysis);
                await _context.SaveChangesAsync();
            }
        }

        public async Task<bool> ExistsAsync(int id)
        {
            return await _context.SkincareAnalyses.AnyAsync(a => a.Id == id);
        }

        public async Task<Dictionary<string, double>> GetSkinTypeTrendAsync(int userId, int months = 6)
        {
            var startDate = DateTime.Today.AddMonths(-months);
            var endDate = DateTime.Today;

            var analyses = await _context.SkincareAnalyses
                .Where(a => a.UserId == userId && 
                           a.AnalysisDate >= startDate && 
                           a.AnalysisDate <= endDate)
                .OrderBy(a => a.AnalysisDate)
                .ToListAsync();

            var trend = new Dictionary<string, double>();

            if (analyses.Any())
            {
                // 计算皮肤类型趋势
                var oilinessTrend = analyses.Average(a => a.OilinessScore);
                var moistureTrend = analyses.Average(a => a.MoistureScore);
                var sensitivityTrend = analyses.Average(a => a.SensitivityScore);
                var elasticityTrend = analyses.Average(a => a.ElasticityScore);

                trend["Oiliness"] = oilinessTrend;
                trend["Moisture"] = moistureTrend;
                trend["Sensitivity"] = sensitivityTrend;
                trend["Elasticity"] = elasticityTrend;
            }

            return trend;
        }

        public async Task<Dictionary<string, string>> GetSkinConcernsAsync(int userId)
        {
            var latestAnalysis = await GetLatestByUserIdAsync(userId);
            if (latestAnalysis == null)
                return new Dictionary<string, string>();

            var concerns = new Dictionary<string, string>();

            // 根据分析结果确定皮肤问题
            if (latestAnalysis.OilinessScore > 7)
                concerns["Oiliness"] = "油性皮肤";
            else if (latestAnalysis.OilinessScore < 3)
                concerns["Dryness"] = "干性皮肤";

            if (latestAnalysis.MoistureScore < 4)
                concerns["Dehydration"] = "缺水";

            if (latestAnalysis.SensitivityScore > 6)
                concerns["Sensitivity"] = "敏感性皮肤";

            if (latestAnalysis.ElasticityScore < 5)
                concerns["LossOfElasticity"] = "弹性不足";

            return concerns;
        }
    }
}